package tk.mybatis.springboot.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.springboot.common.BaseResponse;
import tk.mybatis.springboot.common.ErrorEnum;
import tk.mybatis.springboot.dto.CountryDto;
import tk.mybatis.springboot.service.CountryService;

import java.util.List;

/**
 *
 *
 */
@Controller
@RequestMapping(value = "/countries")
public class CountryApiController extends BaseApiController {

    @Autowired
    private CountryService countryService;


    @RequestMapping(value = "/query")
    @ResponseBody
    public BaseResponse query(@RequestBody CountryDto country) {
        List<CountryDto> countryList = countryService.query(country);
        if (country.getPageNo() != null && country.getPageSize() != null) {
            return success(new PageInfo<CountryDto>(countryList));
        }
        return success(countryList);
    }

    @RequestMapping(value = "/getById")
    @ResponseBody
    public BaseResponse getById(@RequestBody CountryDto country) {
        if(country.idNull()){
            return error(ErrorEnum.PK_NOT_NULL);
        }
        return success(countryService.getById(country.getId()));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse save(@RequestBody @Validated CountryDto country) {
        countryService.save(country);
        return success();
    }

    @RequestMapping(value = "/updateById", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse updateById(@RequestBody CountryDto country) {
        if(country.idNull()){
            return error(ErrorEnum.PK_NOT_NULL);
        }
        if (country.isUpdateIgnoreNull()) {
            countryService.updateIgnoreNullById(country);
        } else {
            countryService.updateById(country);
        }
        return success();
    }

    @RequestMapping(value = "/deleteById")
    @ResponseBody
    public BaseResponse deleteById(@RequestBody CountryDto country) {
        if(country.idNull()){
            return error(ErrorEnum.PK_NOT_NULL);
        }
        countryService.deleteById(country.getId());
        return success();
    }

}
